package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetUserConsumeParam(param map[string]interface{}) (*models_main.UserConsume, error) {
	fName := "GetUserConsumeParam"
	o := &models_main.UserConsume{}
	table := mysql.GetRTable(&models_main.UserConsume{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func InsertUserConsumeByTransactions(session *gorm.DB, consume *models_main.UserConsume) error {
	fName := "InsertUserConsumeByTransactions"
	err := session.Create(consume).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdateUserConsumeByTransactions(session *gorm.DB, columns []string, consume *models_main.UserConsume) error {
	fName := "UpdateUserConsumeByTransactions"
	err := session.Where("id = ?", consume.Id).Select(columns).Updates(consume).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
